/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.swapper.json.spi.supports.time;

import com.swapper.json.*;
import com.swapper.json.reflect.FieldAttributes;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * The {@link LocalDateTime} wrapper factory.
 */
public enum LocalDateTimeWrapperFactory implements JsonWrapperFactory {
  INSTANCE;

  @SuppressWarnings("unchecked")
  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Type type) {
    return type == LocalDateTime.class
      ? (JsonWrapper<T>) new Wrapper(null) : null;
  }

  @SuppressWarnings("unchecked")
  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Field field) {
    return field.getType() == LocalDateTime.class
      ? (JsonWrapper<T>) new Wrapper(FieldAttributes.findDateTimeFormatter(field))
      : null;
  }

  public static final class Wrapper implements JsonWrapper<LocalDateTime> {
    private final DateTimeFormatter _formatter;

    public Wrapper(DateTimeFormatter formatter) {
      _formatter = formatter;
    }

    @Override
    public JsonValue wrap(LocalDateTime value) {
      if (value == null) {
        return JsonValue.NULL;
      }
      if (_formatter == null) {
        return JsonString.valueOf(value.toString());
      } else {
        return JsonString.valueOf(_formatter.format(value));
      }
    }

    @Override
    public LocalDateTime unwrap(JsonValue value) {
      if (JsonValue.NULL.equals(value)) {
        return null;
      }
      if (_formatter == null) {
        return LocalDateTime.parse(value.toString());
      } else {
        return LocalDateTime.parse(value.toString(), _formatter);
      }
    }
  }
}
